package com.myx.typhoon.sys.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.myx.typhoon.business.domain.User;
import com.myx.typhoon.business.domain.UserExample;
import com.myx.typhoon.business.domain.UserExample.Criteria;
import com.myx.typhoon.business.mapper.UserMapper;
import com.myx.typhoon.common.util.MD5Util;
import com.myx.typhoon.sys.service.UserService;

/**  
 * @author myx
 * @createTime 2016年1月18日 下午3:33:33  
 * 
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Resource
	private UserMapper userMapper;
	
	public User findUserByUserName(String username) {
		List<User> list = null;
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		try {
			list = userMapper.selectByExample(example);
		} catch (Exception e) {
			logger.error("findUserByUserName", e);
		}
		if(!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public User findUserByEmail(String email) {
		List<User> list = null;
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andEmailEqualTo(email);
		try {
			list = userMapper.selectByExample(example);
		} catch (Exception e) {
			logger.error("findUserByEmail", e);
		}
		if(!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public int saveUser(User user) {
		user.setPassword(MD5Util.getMD5String(user.getPassword()));
		user.setUpdateTime(new Date());
		int count = 0;
		try {
			count = userMapper.insertSelective(user);
		} catch (Exception e) {
			logger.error("saveUser" ,e);
		}
		return count;
	}

	@Override
	public User findUserById(Long id) {
		try {
			return userMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			logger.error("findUserById",e);
		}
		return null;
	}
}
